import ComponentBase from "../engine/ComponentBase";
import DateUtil from "../engine/DateUtil";
import { EventManager } from "../engine/EventManager";
import { Logger } from "../engine/Logger";
import { EventConfig } from "../game/config/EventConfig";
import { GameConfig } from "../game/config/GameConfig";

import { RoomModel } from "../game/model/RoomModel";
import { RoomPlayer } from "../game/model/RoomPlayer";
import { UIHelper } from "../game/util/UIHelper";
import { SocketClient } from "../net/SocketClient";
import { VoiceSdkHelper } from "../sdk/VoiceSdkHelper";

const { ccclass, property } = cc._decorator;

@ccclass
export default class VoicePrefab extends ComponentBase {

    private btnVoice: cc.Node
    private voiceNode: cc.Node;
    private _lastTouchTime: number = 0
    private isOnRecord: boolean = false
    private _lastCheckTime: number = 0
    private volumeIcon: cc.Node

    private _voiceMsgQueue: Array<object> = []
    private isPlaying: boolean = false
    private _lastPlayTime: number = 0

    private voicePlayNode: cc.Node
    private playCount: number = 0

    onEnable(): void {
        super.onEnable()
        EventManager.instance.on(EventConfig.Event_notify_voice_msg, this.onServerVoiceMsg, this)
        this.voiceNode = this.findChild(this.node, "voiceNode")
        this.voiceNode.active = false
        this.volumeIcon = this.findChild(this.voiceNode, "volumeIcon")
        this.btnVoice = this.findChild(this.node, "btnVoice")
        this.btnVoice.active = false
        this.btnVoice.on(cc.Node.EventType.TOUCH_START, () => {
            this.onVoiceStart()
        });

        this.btnVoice.on(cc.Node.EventType.TOUCH_END, () => {
            if (Date.now() - this._lastTouchTime < 1000) {
                UIHelper.showTip("语音时间小于1秒，不能发送")
                this.onVoiceCancel()
            }
            else {
                this.onVoiceOK()
            }
        });

        this.btnVoice.on(cc.Node.EventType.TOUCH_CANCEL, () => {
            this.onVoiceCancel()
        });

        this.voicePlayNode = this.findChild(this.node, "voicePlayNode")
        this.voicePlayNode.active = false
    }

    private onVoiceStart() {
        if(RoomModel.instance.conf["limit_voice"] == 1){
            UIHelper.showTip("房间禁止使用语音哦")
        }else{
            if (!this.isOnRecord) {
                this.isOnRecord = true
                this._lastTouchTime = DateUtil.now()
                Logger.log("onVoiceStart===", this._lastTouchTime)
                this.voiceNode.active = true
                this.scheduleOnce(() => {
                    this.onVoiceOK()
                }, 5)
                VoiceSdkHelper.prepare()
            }
        }
    }

    private onVoiceCancel() {
        Logger.log("onVoiceCancel===", this._lastTouchTime)
        VoiceSdkHelper.cancel()
        this.disposeVoice()
    }

    private onVoiceOK() {
        this.unscheduleAllCallbacks()
        if(this._lastTouchTime != 0){
            VoiceSdkHelper.finishRecord()
            let time: number = DateUtil.now() - this._lastTouchTime;
            Logger.log("onVoiceOK===", this._lastTouchTime, time)
            if(time >= 2000){
                let msg: string = VoiceSdkHelper.getVoiceData()
                SocketClient.req_voice_msg(msg, time)
            }
            // this.testPlay(msg, time)
        }
        this.disposeVoice()
    }

    private disposeVoice() {
        this.unscheduleAllCallbacks()
        this._lastTouchTime = 0
        this.voiceNode.active = false
        this.isOnRecord = false
    }

    protected update(dt: number): void {
        if(RoomModel.instance.conf["limit_voice"] == 1){
            this.btnVoice.active = false
        }else{
            // this.btnVoice.active = true
        }
        if (this.voiceNode.active) {
            if (Date.now() - this._lastCheckTime > 300) {
                for (var i = 0; i < this.volumeIcon.children.length; ++i) {
                    this.volumeIcon.children[i].active = false;
                }
                let v = VoiceSdkHelper.getVoiceLevel(7);
                if (v >= 1 && v <= 7) {
                    this.volumeIcon.children[v - 1].active = true;
                }
                this._lastCheckTime = Date.now();
            }
        }
        this.playVoiceMsg()
        if (this._lastPlayTime != 0 && DateUtil.now() >= this._lastPlayTime) {
            this.isPlaying = false
            this._lastPlayTime = 0
            cc.audioEngine.resumeAll()
        }
        if (this.isPlaying) {
            this.voicePlayNode.active = true
            for (let i = 0; i < this.voicePlayNode.childrenCount; i++) {
                if (i == this.playCount) {
                    this.voicePlayNode.children[i].active = true
                } else {
                    this.voicePlayNode.children[i].active = false
                }
            }
            this.playCount++
            if (this.playCount >= this.voicePlayNode.childrenCount) {
                this.playCount = 0
            }
        } else {
            this.voicePlayNode.active = false
        }
    }

    private onServerVoiceMsg(data: object) {
        Logger.log("onServerVoiceMsg", data["time"], this._voiceMsgQueue.length)
        if(this._voiceMsgQueue.length <= 0){
            this._voiceMsgQueue.push(data)
            this.playVoiceMsg()
        }
    }

    private playVoiceMsg() {
        if (!this.isPlaying) {
            if (this._voiceMsgQueue.length > 0) {
                this.isPlaying = true
                cc.audioEngine.pauseAll()
                this.playCount = 0
                let data: object = this._voiceMsgQueue.shift()
                let time: number = data["time"] + 1000
                this._lastPlayTime = DateUtil.now() + time
                Logger.log("playVoiceMsg===", time)
                VoiceSdkHelper.writeVoice(data["msg"])
                VoiceSdkHelper.play()
                let userid: number = data["userid"]
                let player: RoomPlayer = RoomPlayer.getPlayerByUserId(userid)
                let seat: number = RoomPlayer.getSeatByChair_ni(player.chair)
                let loc: cc.Vec2
                // if (RoomModel.instance.gameType == GameConfig.Game_Type.huanghua_mj) {
                //     // loc = huanghua_mj_Gamemanager.instance.playerManager.locationList[seat]
                //     loc = huanghua_mj_Gamemanager.instance.playerManager.getSeatLocation(seat)
                // }
                // else if (RoomModel.instance.gameType == GameConfig.Game_Type.ddz) {
                //     loc = DdzGameManager.instance.playerManager.getSeatLocation(seat)
                // }
                // else if (RoomModel.instance.gameType == GameConfig.Game_Type.jianziding) {
                //     loc = jianziding_GameManager.instance.playerManager.getSeatLocation(seat)
                // }
                // else if (RoomModel.instance.gameType == GameConfig.Game_Type.cangxian_mj) {
                //     loc = cangxian_mj_Gamemanager.instance.playerManager.getSeatLocation(seat)
                // }
                // else if (RoomModel.instance.gameType == GameConfig.Game_Type.paodekuai) {
                //     loc = PaodekuaiGameManager.instance.playerManager.getSeatLocation(seat)
                // }
                // else if (RoomModel.instance.gameType == GameConfig.Game_Type.dazhonger_mj) {
                //     loc = dazhonger_mj_Gamemanager.instance.playerManager.getSeatLocation(seat)
                // }
                this.voicePlayNode.setPosition(loc)
            }
        }
    }

    private testPlay(msg: string, time: number) {
        this._lastPlayTime = DateUtil.now() + time
        this.isPlaying = true
        this.playCount = 0
        Logger.log("testPlay===", time)
        VoiceSdkHelper.writeVoice(msg)
        VoiceSdkHelper.play()
    }

}
